package org.sshbot;

import java.util.Locale;

import org.sshbot.util.Utils;

import com.securecrt.SaveSession;
import com.securecrt.pojo.SQLHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class Telnet extends Activity {

	Button btlogintelnet;
	Button btBack, btHome,btvn,bten,btkr;
	Spinner protocolTelnet;
	public String Server="ftp.elisoft.co.kr";
	EditText txtHostname;
	EditText txtPort;
	TextView tvprotocol,tvHostname,tvPort,tvlinksession;
	CheckBox save_session;
	ProgressDialog pro;
	private boolean checked=false;
	SQLHelper eventsData;

//	final TelnetClient telnet=new TelnetClient();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.telnet);
        
        protocolTelnet = (Spinner)findViewById(R.id.protocolTelnet);
        btlogintelnet=(Button)findViewById(R.id.btlogintelnet);
        txtHostname=(EditText)findViewById(R.id.txtHostname);
        txtPort=(EditText)findViewById(R.id.txtPort);
        
        btBack = (Button) findViewById(R.id.btBack);
		btHome = (Button) findViewById(R.id.btHome);
		btBack.setOnClickListener(onBackClick());
		btHome.setOnClickListener(onHomeClick());
        
        ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.protocol ,android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        protocolTelnet.setAdapter(adapter);
        protocolTelnet.setSelection(0);
        protocolTelnet.setOnItemSelectedListener(new OnItemSelectedListener() {

			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				String name = parent.getItemAtPosition(position).toString();
				if(name.equals("telnet")){
					return;
				}
				String classSelected = "org.sshbot." + name.toUpperCase();
				Intent intent = new Intent(classSelected);
				startActivity(intent);
				finish();
			}

			@Override
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				
			}
		});
//        protocolTelnet.setOnItemSelectedListener(new OnItemSelectedListener() {
//			@Override
//			public void onItemSelected(AdapterView<?> parent, View view,
//					int position, long id) {
//				String name = parent.getItemAtPosition(position).toString();
//				if(name.equals("telnet")){
//					return;
//				}
//				String classSelected = "org.sshbot." + name.toUpperCase();
//				Intent intent = new Intent(classSelected);
//				startActivity(intent);
//				finish();
//			}
//			@Override
//			public void onNothingSelected(AdapterView<?> arg0) {
//			}
//        });
        
        
        btlogintelnet.setOnClickListener(new Button.OnClickListener(){

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				OpenTerminal();
			}
        	
        });

		tvprotocol=(TextView)findViewById(R.id.tvprotocol);
		tvHostname=(TextView)findViewById(R.id.tvHostname);
		tvPort=(TextView)findViewById(R.id.tvPort);
        btvn=(Button)findViewById(R.id.btvn);btvn.setOnClickListener(onClickbtvn());
        bten=(Button)findViewById(R.id.bten);bten.setOnClickListener(onClickbten());
        btkr=(Button)findViewById(R.id.btkr);btkr.setOnClickListener(onClickbtkr());
        
        tvlinksession=(TextView)findViewById(R.id.tvlinksession);
        tvlinksession.setOnClickListener(OnClickLinksession);
        
        save_session=(CheckBox)findViewById(R.id.save_session);
        save_session.setOnCheckedChangeListener(ChecKedChangeListener);
        eventsData=new SQLHelper(this);
    }
    private void saveSessionActive(){
    	SQLiteDatabase db=eventsData.getWritableDatabase();
		ContentValues values=new ContentValues();
		values.put(SQLHelper.HOSTNAME, tvHostname.getText().toString());
		values.put(SQLHelper.PORT, tvPort.getText().toString());
		db.insert(SQLHelper.SESSION, null, values);
    }
    private OnCheckedChangeListener ChecKedChangeListener=new OnCheckedChangeListener() {
		
		@Override
		public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			// TODO Auto-generated method stub
			if(buttonView.isChecked()){
				checked=true;
			}else{
				checked=false;
			}
		}
	};
    private OnClickListener OnClickLinksession=new OnClickListener() {
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			passSaveSession();
		}
	};
    private void passSaveSession(){
    	Intent i=new Intent(this, SaveSession.class);
    	i.putExtra("host",tvHostname.getText().toString());
		i.putExtra("port", tvPort.getText().toString());
    	startActivity(i);
    }
    private void refresh() {
        finish();
        Intent myIntent = new Intent(Telnet.this, Telnet.class);
        startActivity(myIntent);
    }
    private void changuageLang(String lang){
		Locale locale=new Locale(lang);
        Locale.setDefault(locale);
        Configuration config=new Configuration();
        config.locale=locale;
        getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    }
    private OnClickListener onClickbtvn(){
    	OnClickListener onClickbtvn=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("vn");refresh();
			}
		};
    	return onClickbtvn;
    }
    private OnClickListener onClickbten(){
    	OnClickListener onClickbten=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("en");refresh();
			}
		};
    	return onClickbten;
    }

    private OnClickListener onClickbtkr(){
    	OnClickListener onClickbtkr=new OnClickListener() {
			@Override
			public void onClick(View v) {
				changuageLang("kr");refresh();
			}
		};
    	return onClickbtkr;
    }

    private void OpenTerminal(){
    	loadingShow();
    	if(txtHostname.getText().toString().trim().equals("")){
    		Toast.makeText(this, "Server name is not empty!", Toast.LENGTH_LONG).show();
    		return;
		}
    	String sPort=txtPort.getText().toString().trim();
    	boolean isBadPort=false;
    	int iPort=0;
    	try{
    		iPort=Integer.parseInt(sPort);
    	}
    	catch (Exception e) {
			isBadPort=true;
		}
    	if(iPort<=0||iPort>=65535){
    		isBadPort=true;
    	}
    	if(isBadPort){
    		Utils.showErrorMessage(this,"Bad port number.");
    		//Toast.makeText(this, "Bad port number!", Toast.LENGTH_LONG).show();
    		return;
    	}
    	Editor ed=this.getPreferences(0).edit();
    	ed.putString("server", txtHostname.getText().toString());
    	ed.putString("port", txtPort.getText().toString());
    	ed.commit();
    	try{
        	if(checkLoginTelnet(txtHostname.getText().toString(), iPort)){
        		if(checked){
					//save session
					saveSessionActive();
				}
//        		Toast.makeText(this, "Telnet Connect Success.", Toast.LENGTH_LONG).show();
//            	Intent i=new Intent(this, terminalTelnet.class);
//            	i.putExtra("server", txtHostname.getText().toString());
//            	i.putExtra("port", iPort);
//            	startActivity(i);
//            	telnet.disconnect();
        	}
        	else{
        		Utils.showErrorMessage(this,"Telnet Connect Fault.");
        		pro.dismiss();
        		//Toast.makeText(this, "That bai", Toast.LENGTH_LONG).show();
        		return;
        	}
    	}
    	catch (Exception e) {
    		System.out.println("Telnet.con "+e.getStackTrace());
    	}
    	
	}
    
    private void loadingShow(){
    	pro=ProgressDialog.show(this, "", "Please wait...");
    	
    }

    private boolean checkLoginTelnet(String hostname,int port){
    	
    	boolean flag=false;
    	//    		telnet.setConnectTimeout(5000);
//        	telnet.connect(hostname, port);
		flag=true;
    	return flag;
    }

	
	private OnClickListener onBackClick() {
		OnClickListener onBackClick = new OnClickListener() {
			@Override
			public void onClick(View v) {
				//moveTaskToBack(true);
				finish();
				System.exit(0);
			}
		};
		return onBackClick;
	}
	
	private OnClickListener onHomeClick() {
		OnClickListener onHomeClick = new OnClickListener() {
			@Override
			public void onClick(View v) {

				Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
				finish();
				System.exit(0);

			}
		};
		return onHomeClick;
	}
}
